package it.tukano.treditor.modules;

import it.tukano.app.AbstractAppModule;
import it.tukano.app.AppModule;
import it.tukano.io.FileExt;
import java.io.Serializable;

/**
 * This module manages the application's settings (frame size, position, colors,
 * things like that)
 * @author pgi
 */
public class AppSettingsModule extends AbstractAppModule {
    
    private FileExt base;
    /**
     * Instance initializer
     */
    public AppSettingsModule() {
    }
    
    /**
     * Saves or replaces a value in the persistent map
     * @param name the name of the value to set
     * @param value the new value. Cannot be null.
     */
    public synchronized void saveSetting(String name, Serializable value) {
        FileExt file = getSerializedObjectFile(name);
        file.storeSerializableObject(value);
    }
    
    public synchronized <T extends Serializable> T getSettingOrElse(Class<T> valueType, String name, T defaultValue) {
        FileExt file = getSerializedObjectFile(name);
        if(file.exists()) {
            Object value = file.readSerializedObject();
            if(value != null && valueType.isAssignableFrom(value.getClass())) return valueType.cast(value);
            return null;
        } else {
            return defaultValue;
        }
    }

    @Override
    public void initModule(AppModule context) {
        
        super.initModule(context);
        FileExt folder = FileExt.getJarFolder(AppSettingsModule.class);
        FileExt base = folder.getChild("3dtorsettings");
        if(!base.exists()) base.mkDirs();
        synchronized (this) {
            this.base = base;
        }
    }

    /* pre: synchronized (this) */
    private FileExt getSerializedObjectFile(String name) {
        FileExt file = new FileExt(base, name.hashCode() + ".ser");
        return file;
    }
    
}
